<!DOCTYPE html>












  


<html class="theme-next gemini use-motion" lang="zh-CN">
<head><meta name="generator" content="Hexo 3.8.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">




  
  
    
    
  <script src="/blog/lib/pace/pace.min.js?v=1.0.2"></script>
  <link rel="stylesheet" href="/blog/lib/pace/pace-theme-minimal.min.css?v=1.0.2">





















<link rel="stylesheet" href="/blog/lib/font-awesome/css/font-awesome.min.css?v=4.6.2">

<link rel="stylesheet" href="/blog/css/main.css?v=7.1.0">


  <link rel="apple-touch-icon" sizes="180x180" href="/blog/images/apple-touch-icon-next.png?v=7.1.0">


  <link rel="icon" type="image/png" sizes="32x32" href="/blog/images/favicon-32x32-next.png?v=7.1.0">


  <link rel="icon" type="image/png" sizes="16x16" href="/blog/images/favicon-16x16-next.png?v=7.1.0">


  <link rel="mask-icon" href="/blog/images/logo.svg?v=7.1.0" color="#222">







<script id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/blog/',
    scheme: 'Gemini',
    version: '7.1.0',
    sidebar: {"position":"left","display":"post","offset":12,"onmobile":false,"dimmer":false},
    back2top: true,
    back2top_sidebar: false,
    fancybox: false,
    fastclick: false,
    lazyload: false,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>


  




  <meta name="description" content="如果你跟我一样想要自己开发公众号的，却不知道怎么开始？那就来看我的这篇文章吧，跟着我的步伐，带你一步一步搭建自己的微信公众号！！！Come on!">
<meta name="keywords" content="微信,公众号,Java">
<meta property="og:type" content="article">
<meta property="og:title" content="从零接入微信公众号（附源码+解说）">
<meta property="og:url" content="http://zwd596257180.gitee.io/2019/04/16/wechat_account/index.html">
<meta property="og:site_name" content="东Ge博客">
<meta property="og:description" content="如果你跟我一样想要自己开发公众号的，却不知道怎么开始？那就来看我的这篇文章吧，跟着我的步伐，带你一步一步搭建自己的微信公众号！！！Come on!">
<meta property="og:locale" content="zh-CN">
<meta property="og:image" content="http://zwd.yyzheng.cn/wechat_account/030e7ee3351c74bfs.jpg">
<meta property="og:updated_time" content="2019-05-13T02:38:31.406Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="从零接入微信公众号（附源码+解说）">
<meta name="twitter:description" content="如果你跟我一样想要自己开发公众号的，却不知道怎么开始？那就来看我的这篇文章吧，跟着我的步伐，带你一步一步搭建自己的微信公众号！！！Come on!">
<meta name="twitter:image" content="http://zwd.yyzheng.cn/wechat_account/030e7ee3351c74bfs.jpg">



  <link rel="alternate" href="/blog/atom.xml" title="东Ge博客" type="application/atom+xml">



  
  
  <link rel="canonical" href="http://zwd596257180.gitee.io/2019/04/16/wechat_account/">



<script id="page.configurations">
  CONFIG.page = {
    sidebar: "",
  };
</script>

  <title>从零接入微信公众号（附源码+解说） | 东Ge博客</title>
  












  <noscript>
  <style>
  .use-motion .motion-element,
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-title { opacity: initial; }

  .use-motion .logo,
  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-CN">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>
    <a href="https://github.com/yyzheng1729" class="github-corner" aria-label="View source on GitHub"><svg width="80" height="80" viewbox="0 0 250 250" style="fill:#151513; color:#fff; position: absolute; top: 0; border: 0; right: 0;" aria-hidden="true"><path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"/><path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2" fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"/><path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z" fill="currentColor" class="octo-body"/></svg></a><style>.github-corner:hover .octo-arm{animation:octocat-wave 560ms ease-in-out}@keyframes octocat-wave{0%,100%{transform:rotate(0)}20%,60%{transform:rotate(-25deg)}40%,80%{transform:rotate(10deg)}}@media (max-width:500px){.github-corner:hover .octo-arm{animation:none}.github-corner .octo-arm{animation:octocat-wave 560ms ease-in-out}}</style>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta">
    

    <div class="custom-logo-site-title">
      <a href="/blog/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">东Ge博客</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
    
      
        <p class="site-subtitle">http://zwd596257180.gitee.io</p>
      
    
    
  </div>

  <div class="site-nav-toggle">
    <button aria-label="切换导航栏">
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>



<nav class="site-nav">
  
    <ul id="menu" class="menu">
      
        
        
        
          
          <li class="menu-item menu-item-home">

    
    
    
      
    

    

    <a href="/blog/" rel="section"><i class="menu-item-icon fa fa-fw fa-home"></i> <br>首页</a>

  </li>
        
        
        
          
          <li class="menu-item menu-item-about">

    
    
    
      
    

    

    <a href="/blog/about/" rel="section"><i class="menu-item-icon fa fa-fw fa-user"></i> <br>关于</a>

  </li>
        
        
        
          
          <li class="menu-item menu-item-tags">

    
    
    
      
    

    

    <a href="/blog/tags/" rel="section"><i class="menu-item-icon fa fa-fw fa-tags"></i> <br>标签</a>

  </li>
        
        
        
          
          <li class="menu-item menu-item-categories">

    
    
    
      
    

    

    <a href="/blog/categories/" rel="section"><i class="menu-item-icon fa fa-fw fa-th"></i> <br>分类</a>

  </li>
        
        
        
          
          <li class="menu-item menu-item-archives">

    
    
    
      
    

    

    <a href="/blog/archives/" rel="section"><i class="menu-item-icon fa fa-fw fa-archive"></i> <br>归档</a>

  </li>

      
      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br>搜索</a>
        </li>
      
    </ul>
  

  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off" placeholder="搜索..." spellcheck="false" type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



  



</div>
    </header>

    


    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          
            

          
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    
  

  
  
  

  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  

  

  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://zwd596257180.gitee.io/blog/2019/04/16/wechat_account/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="小东">
      <meta itemprop="description" content="欢迎您的到来！">
      <meta itemprop="image" content="https://wx.qlogo.cn/mmopen/vi_32/GqPMLROFPOIvfCs85HKcD1UKwt3zEJOK4yIcJKaSz4lFGTaL8EzBmziczWx9oWbHyAIBcjwAMXviayrzkpYmzzvg/132">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="东Ge博客">
    </span>

    
      <header class="post-header">

      

        
        
          <h1 class="post-title" itemprop="name headline">从零接入微信公众号（附源码+解说）

              
            
          </h1>
        

        <div class="post-meta">
          <span class="post-time">

            
            
            

            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              

              
                
              

              <time title="创建时间：2019-04-16 00:00:00" itemprop="dateCreated datePublished" datetime="2019-04-16T00:00:00+08:00">2019-04-16</time>
            

            
              

              
                
                <span class="post-meta-divider">|</span>
                

                <span class="post-meta-item-icon">
                  <i class="fa fa-calendar-check-o"></i>
                </span>
                
                  <span class="post-meta-item-text">更新于</span>
                
                <time title="修改时间：2019-05-13 10:38:31" itemprop="dateModified" datetime="2019-05-13T10:38:31+08:00">2019-05-13</time>
              
            
          </span>

          
            <span class="post-category">
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing"><a href="/blog/categories/微信公众号/" itemprop="url" rel="index"><span itemprop="name">微信公众号</span></a></span>

                
                
              
            </span>
          

          
            
            
          

          
          

          

          

          
            <div class="post-description">如果你跟我一样想要自己开发公众号的，却不知道怎么开始？那就来看我的这篇文章吧，跟着我的步伐，带你一步一步搭建自己的微信公众号！！！Come on!</div>
          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      
        <div class="post-gallery" itemscope itemtype="http://schema.org/ImageGallery">
          
          
            <div class="post-gallery-row">
              <img src="http://zwd.yyzheng.cn/wechat_account/030e7ee3351c74bfs.jpg" itemprop="contentUrl">
            
          

          
          </div>
        </div>
      

      
        <h1 id="前言"><a href="#前言" class="headerlink" title="前言"></a>前言</h1><ol>
<li>一台云服务器（配置 web 项目环境）</li>
<li>一个域名（https）</li>
</ol>
<p>关于服务器方面的，如果你是个小白，可以看下我其它的博客：</p>
<p><a href="https://blog.csdn.net/weidong_y/article/details/80365271" target="_blank" rel="noopener">CentOS 服务器配置 jdk +Tomcat + mysql</a></p>
<p><a href="https://blog.csdn.net/weidong_y/article/details/80554279" target="_blank" rel="noopener">基于腾讯云的域名绑定和 tomcat 部署</a></p>
<p><a href="https://blog.csdn.net/weidong_y/article/details/80555382" target="_blank" rel="noopener">腾讯云申请免费 ssl 证书+tomcat配置https</a></p>
<table><tr><td bgcolor="#C0FF3E">本文是直接上代码，有些需要修改和解释都会说明。</td></tr></table>

<h1 id="实现接口连接的类"><a href="#实现接口连接的类" class="headerlink" title="实现接口连接的类"></a>实现接口连接的类</h1><p>我的 web 开发环境是用 SSM 和 maven 搭建的，不懂可以看我的之前的博客：</p>
<p><a href="https://blog.csdn.net/weidong_y/article/details/80800191" target="_blank" rel="noopener">eclipse+maven 配置SSM项目环境</a></p>
<font color="#dd0000" size="5">SignUtil.java 的实现代码</font> 

<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> java.security.MessageDigest;</span><br><span class="line"><span class="keyword">import</span> java.security.NoSuchAlgorithmException;</span><br><span class="line"><span class="keyword">import</span> java.util.Arrays;</span><br><span class="line"> </span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 微信请求校验工具类</span></span><br><span class="line"><span class="comment"> * </span></span><br><span class="line"><span class="comment"> * <span class="doctag">@author</span> yy</span></span><br><span class="line"><span class="comment"> *</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">SignUtil</span> </span>&#123;</span><br><span class="line">	<span class="comment">// 与接口配置信息中的 Token 要一致</span></span><br><span class="line">	<span class="keyword">private</span> <span class="keyword">static</span> String token = <span class="string">"o2o"</span>;</span><br><span class="line"> </span><br><span class="line">	<span class="comment">/**</span></span><br><span class="line"><span class="comment">	 * 验证签名</span></span><br><span class="line"><span class="comment">	 * </span></span><br><span class="line"><span class="comment">	 * <span class="doctag">@param</span> signature</span></span><br><span class="line"><span class="comment">	 * <span class="doctag">@param</span> timestamp</span></span><br><span class="line"><span class="comment">	 * <span class="doctag">@param</span> nonce</span></span><br><span class="line"><span class="comment">	 * <span class="doctag">@return</span></span></span><br><span class="line"><span class="comment">	 */</span></span><br><span class="line">	<span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">boolean</span> <span class="title">checkSignature</span><span class="params">(String signature, String timestamp, String nonce)</span> </span>&#123;</span><br><span class="line">		String[] arr = <span class="keyword">new</span> String[] &#123; token, timestamp, nonce &#125;;</span><br><span class="line">		<span class="comment">// 將 token timestamp nonce 三个参数进行字典序排序</span></span><br><span class="line">		Arrays.sort(arr);</span><br><span class="line">		StringBuilder content = <span class="keyword">new</span> StringBuilder();</span><br><span class="line">		<span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; arr.length; i++) &#123;</span><br><span class="line">			content.append(arr[i]);</span><br><span class="line">		&#125;</span><br><span class="line">		MessageDigest md = <span class="keyword">null</span>;</span><br><span class="line">		String tmpStr = <span class="keyword">null</span>;</span><br><span class="line">		<span class="keyword">try</span> &#123;</span><br><span class="line">			md = MessageDigest.getInstance(<span class="string">"SHA-1"</span>);</span><br><span class="line">			<span class="comment">// 将三个参数字符串拼接成一个字符串进行sha1加密</span></span><br><span class="line">			<span class="keyword">byte</span>[] digest = md.digest(content.toString().getBytes());</span><br><span class="line">			tmpStr = byteToStr(digest);</span><br><span class="line">		&#125; <span class="keyword">catch</span> (NoSuchAlgorithmException e) &#123;</span><br><span class="line">			e.printStackTrace();</span><br><span class="line">		&#125;</span><br><span class="line">		content = <span class="keyword">null</span>;</span><br><span class="line">		<span class="comment">// 将sha1加密后的字符串可与signature对比，标识该请求来源于微信</span></span><br><span class="line">		<span class="keyword">return</span> tmpStr != <span class="keyword">null</span> ? tmpStr.equals(signature.toUpperCase()) : <span class="keyword">false</span>;</span><br><span class="line">	&#125;</span><br><span class="line"> </span><br><span class="line">	<span class="comment">/**</span></span><br><span class="line"><span class="comment">	 * 将字节数组转换为十六进制字符串</span></span><br><span class="line"><span class="comment">	 * </span></span><br><span class="line"><span class="comment">	 * <span class="doctag">@param</span> digest</span></span><br><span class="line"><span class="comment">	 * <span class="doctag">@return</span></span></span><br><span class="line"><span class="comment">	 */</span></span><br><span class="line">	<span class="function"><span class="keyword">private</span> <span class="keyword">static</span> String <span class="title">byteToStr</span><span class="params">(<span class="keyword">byte</span>[] byteArray)</span> </span>&#123;</span><br><span class="line">		String strDigest = <span class="string">""</span>;</span><br><span class="line">		<span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; byteArray.length; i++) &#123;</span><br><span class="line">			strDigest += byteToHexStr(byteArray[i]);</span><br><span class="line">		&#125;</span><br><span class="line">		<span class="keyword">return</span> strDigest;</span><br><span class="line">	&#125;</span><br><span class="line"> </span><br><span class="line">	<span class="comment">/**</span></span><br><span class="line"><span class="comment">	 * 将字符转换为十六进制字符串</span></span><br><span class="line"><span class="comment">	 * </span></span><br><span class="line"><span class="comment">	 * <span class="doctag">@param</span> b</span></span><br><span class="line"><span class="comment">	 * <span class="doctag">@return</span></span></span><br><span class="line"><span class="comment">	 */</span></span><br><span class="line">	<span class="function"><span class="keyword">private</span> <span class="keyword">static</span> String <span class="title">byteToHexStr</span><span class="params">(<span class="keyword">byte</span> mByte)</span> </span>&#123;</span><br><span class="line">		<span class="keyword">char</span>[] Digit = &#123; <span class="string">'0'</span>, <span class="string">'1'</span>, <span class="string">'2'</span>, <span class="string">'3'</span>, <span class="string">'4'</span>, <span class="string">'5'</span>, <span class="string">'6'</span>, <span class="string">'7'</span>, <span class="string">'8'</span>, <span class="string">'9'</span>, <span class="string">'A'</span>, <span class="string">'B'</span>, <span class="string">'C'</span>, <span class="string">'D'</span>, <span class="string">'E'</span>, <span class="string">'F'</span> &#125;;</span><br><span class="line">		<span class="keyword">char</span>[] tempArr = <span class="keyword">new</span> <span class="keyword">char</span>[<span class="number">2</span>];</span><br><span class="line">		tempArr[<span class="number">0</span>] = Digit[(mByte &gt;&gt;&gt; <span class="number">4</span>) &amp; <span class="number">0X0F</span>];</span><br><span class="line">		tempArr[<span class="number">1</span>] = Digit[mByte &amp; <span class="number">0X0F</span>];</span><br><span class="line">		String s = <span class="keyword">new</span> String(tempArr);</span><br><span class="line">		<span class="keyword">return</span> s;</span><br><span class="line">	&#125;</span><br><span class="line"> </span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<font color="#dd0000" size="5">WechatController.java 的实现代码</font> 

<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> java.io.IOException;</span><br><span class="line"><span class="keyword">import</span> java.io.PrintWriter;</span><br><span class="line"> </span><br><span class="line"><span class="keyword">import</span> javax.servlet.http.HttpServletRequest;</span><br><span class="line"><span class="keyword">import</span> javax.servlet.http.HttpServletResponse;</span><br><span class="line"> </span><br><span class="line"><span class="keyword">import</span> org.slf4j.Logger;</span><br><span class="line"><span class="keyword">import</span> org.slf4j.LoggerFactory;</span><br><span class="line"><span class="keyword">import</span> org.springframework.stereotype.Controller;</span><br><span class="line"><span class="keyword">import</span> org.springframework.web.bind.annotation.RequestMapping;</span><br><span class="line"><span class="keyword">import</span> org.springframework.web.bind.annotation.RequestMethod;</span><br><span class="line"> </span><br><span class="line"><span class="keyword">import</span> com.util.wechat.SignUtil;</span><br><span class="line"> </span><br><span class="line"><span class="meta">@Controller</span></span><br><span class="line"><span class="meta">@RequestMapping</span>(<span class="string">"wechat"</span>)</span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">WechatController</span> </span>&#123;</span><br><span class="line">	</span><br><span class="line">	<span class="keyword">private</span> <span class="keyword">static</span> Logger log = LoggerFactory.getLogger(WechatController.class);</span><br><span class="line"> </span><br><span class="line">	<span class="meta">@RequestMapping</span>(method = &#123; RequestMethod.GET &#125;)</span><br><span class="line">	<span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">doGet</span><span class="params">(HttpServletRequest request, HttpServletResponse response)</span> </span>&#123;</span><br><span class="line">		log.debug(<span class="string">"wechat get..."</span>);</span><br><span class="line">		<span class="comment">// 微信加密签名</span></span><br><span class="line">		String signature = request.getParameter(<span class="string">"signature"</span>);</span><br><span class="line">		<span class="comment">// 时间戳</span></span><br><span class="line">		String timestamp = request.getParameter(<span class="string">"timestamp"</span>);</span><br><span class="line">		<span class="comment">// 随机数</span></span><br><span class="line">		String nonce = request.getParameter(<span class="string">"nonce"</span>);</span><br><span class="line">		<span class="comment">// 随机字符串</span></span><br><span class="line">		String echostr = request.getParameter(<span class="string">"echostr"</span>);</span><br><span class="line"> </span><br><span class="line">		<span class="comment">// 通过检验signature对请求进行校验，若校验成功则原样返回echostr，表示接入成功，否则接入失败</span></span><br><span class="line">		PrintWriter out = <span class="keyword">null</span>;</span><br><span class="line">		<span class="keyword">try</span> &#123;</span><br><span class="line">			out = response.getWriter();</span><br><span class="line">			<span class="keyword">if</span> (SignUtil.checkSignature(signature, timestamp, nonce)) &#123;</span><br><span class="line">				log.debug(<span class="string">"wechat get success...."</span>);</span><br><span class="line">				out.print(echostr);</span><br><span class="line">			&#125;</span><br><span class="line">		&#125; <span class="keyword">catch</span> (IOException e) &#123;</span><br><span class="line">			e.printStackTrace();</span><br><span class="line">		&#125; <span class="keyword">finally</span> &#123;</span><br><span class="line">			<span class="keyword">if</span> (out != <span class="keyword">null</span>)</span><br><span class="line">				out.close();</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>到这里为止并不需要去修改什么代码，只需要将工程导出为 jar 包扔到自己的云服务器上就行方便后面微信测试号接口的链接测试。记得要放到服务器上，不然访问不到！！！</p>
<h1 id="微信测试号的申请与接口连接"><a href="#微信测试号的申请与接口连接" class="headerlink" title="微信测试号的申请与接口连接"></a>微信测试号的申请与接口连接</h1><p>刚刚开始做微信公众号的时候，我们建议选择微信测试号就好，等熟悉了之后，微信公众号的配置什么的，跟测试号是一样的。</p>
<p>接下来就教大家怎么来申请测试号。</p>
<p>首先进入微信公众号的开发文档：<a href="https://mp.weixin.qq.com/wiki？t=resource/res_main&amp;id=mp1445241432" target="_blank" rel="noopener">https://mp.weixin.qq.com/wiki？t=resource/res_main&amp;id=mp1445241432</a></p>
<p><img src="http://zwd.yyzheng.cn/wechat_account/89df85ddc635b3ccs.png" alt="Markdown"></p>
<p><img src="http://zwd.yyzheng.cn/wechat_account/078b26bcd8380cfcs.png" alt="Markdown"></p>
<p>点击“接口配置信息”旁边的“修改”按钮，然后按要求填写内容，然后点击提交，会提示你是否能连接上的。</p>
<p><img src="http://zwd.yyzheng.cn/wechat_account/85cd9b5efee19a3ds.png" alt="Markdown"></p>
<p><img src="http://zwd.yyzheng.cn/wechat_account/be824ea5f5cd5c06s.png" alt="Markdown"></p>
<p><img src="http://zwd.yyzheng.cn/wechat_account/4745d58eb89ebb8es.png" alt="Markdown"></p>
<h1 id="微信测试号连接代码的实现"><a href="#微信测试号连接代码的实现" class="headerlink" title="微信测试号连接代码的实现"></a>微信测试号连接代码的实现</h1><h2 id="用到类的简介"><a href="#用到类的简介" class="headerlink" title="用到类的简介"></a>用到类的简介</h2><p>上面测试了微信测试号的接口的可以连接上的，现在来实现手机上的微信测试号是如果连接上的。需要通过五个类来实现，分别是：</p>
<ol>
<li>WechatLoginController.java</li>
<li>UserAccessToken.java </li>
<li>WechatUser.java</li>
<li>WechatUtil.java</li>
<li>MyX509TrustManager.java</li>
</ol>
<p>下面会一一讲解这个5个类的实现，以及一些要修改的地方。</p>
<table><tr><td bgcolor="#C0FF3E">提示：我的代码里面使用 debug 输出信息，如果不需要可以把如下面的代码给删除掉。</td></tr></table>

<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">private</span> <span class="keyword">static</span> Logger log = LoggerFactory.getLogger(WechatLoginController.class);</span><br></pre></td></tr></table></figure>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">log.debug(<span class="string">"weixin login get..."</span>);</span><br></pre></td></tr></table></figure>
<h2 id="WechatLoginController-java-的实现代码"><a href="#WechatLoginController-java-的实现代码" class="headerlink" title="WechatLoginController.java 的实现代码"></a>WechatLoginController.java 的实现代码</h2><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> java.io.IOException;</span><br><span class="line"> </span><br><span class="line"><span class="keyword">import</span> javax.servlet.http.HttpServletRequest;</span><br><span class="line"><span class="keyword">import</span> javax.servlet.http.HttpServletResponse;</span><br><span class="line"> </span><br><span class="line"><span class="keyword">import</span> org.slf4j.Logger;</span><br><span class="line"><span class="keyword">import</span> org.slf4j.LoggerFactory;</span><br><span class="line"><span class="keyword">import</span> org.springframework.stereotype.Controller;</span><br><span class="line"><span class="keyword">import</span> org.springframework.web.bind.annotation.RequestMapping;</span><br><span class="line"><span class="keyword">import</span> org.springframework.web.bind.annotation.RequestMethod;</span><br><span class="line"> </span><br><span class="line"><span class="keyword">import</span> com.dto.UserAccessToken;</span><br><span class="line"><span class="keyword">import</span> com.dto.WechatUser;</span><br><span class="line"><span class="keyword">import</span> com.util.wechat.WechatUtil;</span><br><span class="line"> </span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 获取关注公众号之后的微信用户信息的接口，如果在微信浏览器里访问</span></span><br><span class="line"><span class="comment"> * https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxaxxxxxxxxxxxxx&amp;redirect_uri=https://www.yyzheng.cn/o2o/wechatlogin/logincheck&amp;role_type=1&amp;response_type=1&amp;response_type=code&amp;scope=snsapi_userinfo&amp;state=1#wechat_redirect </span></span><br><span class="line"><span class="comment"> * 则在这里将会获取到code，之后再通过code获取到access_token进而获取到用户信息</span></span><br><span class="line"><span class="comment"> * </span></span><br><span class="line"><span class="comment"> * <span class="doctag">@author</span> yy</span></span><br><span class="line"><span class="comment"> *</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="meta">@Controller</span></span><br><span class="line"><span class="meta">@RequestMapping</span>(<span class="string">"wechatlogin"</span>)</span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">WechatLoginController</span> </span>&#123;</span><br><span class="line">	<span class="keyword">private</span> <span class="keyword">static</span> Logger log = LoggerFactory.getLogger(WechatLoginController.class);</span><br><span class="line"> </span><br><span class="line">	<span class="meta">@RequestMapping</span>(value = <span class="string">"/logincheck"</span>, method = &#123; RequestMethod.GET &#125;)</span><br><span class="line">	<span class="function"><span class="keyword">public</span> String <span class="title">doGet</span><span class="params">(HttpServletRequest request, HttpServletResponse response)</span> </span>&#123;</span><br><span class="line">		log.debug(<span class="string">"weixin login get..."</span>);</span><br><span class="line">		<span class="comment">// 获取微信公众号传输过来的code，通过code可获取access_token,进而获取用户信息</span></span><br><span class="line">		String code = request.getParameter(<span class="string">"code"</span>);</span><br><span class="line">		<span class="comment">// 这个State可以用来传我们自定义的信息，方便程序调用，这里也可以不用</span></span><br><span class="line">		<span class="comment">// String roleType = request.getParameter("state");</span></span><br><span class="line">		log.debug(<span class="string">"weixin login code:"</span> + code);</span><br><span class="line">		WechatUser user = <span class="keyword">null</span>;</span><br><span class="line">		String openId = <span class="keyword">null</span>;</span><br><span class="line">		<span class="keyword">if</span> (<span class="keyword">null</span> != code) &#123;</span><br><span class="line">			UserAccessToken token;</span><br><span class="line">			<span class="keyword">try</span> &#123;</span><br><span class="line">				<span class="comment">// 通过code获取access_token</span></span><br><span class="line">				token = WechatUtil.getUserAccessToken(code);</span><br><span class="line">				log.debug(<span class="string">"weixin login token:"</span> + token.toString());</span><br><span class="line">				<span class="comment">// 通过token获取accessToken</span></span><br><span class="line">				String accessToken = token.getAccessToken();</span><br><span class="line">				<span class="comment">// 通过token获取openId</span></span><br><span class="line">				openId = token.getOpenId();</span><br><span class="line">				<span class="comment">// 通过access_token和openId获取用户昵称等信息</span></span><br><span class="line">				user = WechatUtil.getUserInfo(accessToken, openId);</span><br><span class="line">				log.debug(<span class="string">"weixin login user:"</span> + user.toString());</span><br><span class="line">				request.getSession().setAttribute(<span class="string">"openId"</span>, openId);</span><br><span class="line">			&#125; <span class="keyword">catch</span> (Exception e) &#123;</span><br><span class="line">				log.error(<span class="string">"error in getUserAccessToken or getUserInfo or findByOpenId: "</span> + e.toString());</span><br><span class="line">				e.printStackTrace();</span><br><span class="line">			&#125;</span><br><span class="line">		&#125;</span><br><span class="line"> </span><br><span class="line">		<span class="comment">// ========todo begin ===========</span></span><br><span class="line">		<span class="comment">// 前面咱门获取到openid后，可以通过它去数据库判断该微信账号是否在我们网站里有对应的 账号了</span></span><br><span class="line">		<span class="comment">// 没有的话这里可以自动创建上，直接实现微信与咱门网站的无缝对接</span></span><br><span class="line">		<span class="comment">// ========todo end =============</span></span><br><span class="line"> </span><br><span class="line">		<span class="keyword">if</span> (user != <span class="keyword">null</span>) &#123;</span><br><span class="line">			<span class="comment">// 获取到微信验证的信息后返回到指定的路由（需要自己设定）</span></span><br><span class="line">			<span class="keyword">return</span> <span class="string">"frontend/index"</span>;                                  <span class="comment">/*******修改******/</span></span><br><span class="line">		&#125; <span class="keyword">else</span> &#123;</span><br><span class="line">			<span class="keyword">return</span> <span class="keyword">null</span>;</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<table><tr><td bgcolor="#C0FF3E">解析：这段代码需要注意的是最后这一小段代码。</td></tr></table>

<p><img src="http://zwd.yyzheng.cn/wechat_account/159dd6e3cc3c1712s.png" alt="Markdown"></p>
<p>这里的意思是，用户进入微信公众号后，验证通过，并判断用户不为空，就跳转到自己想要跳转的页面。所有需要修改掉 return 的值，代码的值是返回到我项目里的其他页面。只要返回到一个简单的页面就行，这里只是做个测试，看微信测试号是否真的能够接入成功，成功就跳转。不成功就不跳转。</p>
<h2 id="UserAccessToken-java-的实现代码"><a href="#UserAccessToken-java-的实现代码" class="headerlink" title="UserAccessToken.java  的实现代码"></a>UserAccessToken.java  的实现代码</h2><p>只是一个实体类，用来封装信息的。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> com.fasterxml.jackson.annotation.JsonProperty;</span><br><span class="line"> </span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 用户授权token</span></span><br><span class="line"><span class="comment"> *</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">UserAccessToken</span> </span>&#123;</span><br><span class="line">	</span><br><span class="line">	<span class="comment">//获取到的凭证</span></span><br><span class="line">	<span class="meta">@JsonProperty</span>(<span class="string">"access_token"</span>)</span><br><span class="line">	<span class="keyword">private</span> String accessToken;</span><br><span class="line">	<span class="comment">//凭证有效时间，单位：秒</span></span><br><span class="line">	<span class="meta">@JsonProperty</span>(<span class="string">"expires_in"</span>)</span><br><span class="line">	<span class="keyword">private</span> String expiresIn;</span><br><span class="line">	<span class="comment">//表示更新令牌，用来获取下一次的访问令牌，这里没太大用处</span></span><br><span class="line">	<span class="meta">@JsonProperty</span>(<span class="string">"refresh_token"</span>)</span><br><span class="line">	<span class="keyword">private</span> String refreshToken;</span><br><span class="line">	<span class="comment">//该用户在此公众号下的身份表示，对于此微信号具有唯一性</span></span><br><span class="line">	<span class="meta">@JsonProperty</span>(<span class="string">"openid"</span>)</span><br><span class="line">	<span class="keyword">private</span> String openId;</span><br><span class="line">	<span class="comment">//表示权限范围，这里可省略</span></span><br><span class="line">	<span class="meta">@JsonProperty</span>(<span class="string">"scope"</span>)</span><br><span class="line">	<span class="keyword">private</span> String scope;</span><br><span class="line">	</span><br><span class="line">	<span class="function"><span class="keyword">public</span> String <span class="title">getAccessToken</span><span class="params">()</span> </span>&#123;</span><br><span class="line">		<span class="keyword">return</span> accessToken;</span><br><span class="line">	&#125;</span><br><span class="line"> </span><br><span class="line">	<span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setAccessToken</span><span class="params">(String accessToken)</span> </span>&#123;</span><br><span class="line">		<span class="keyword">this</span>.accessToken = accessToken;</span><br><span class="line">	&#125;</span><br><span class="line"> </span><br><span class="line">	<span class="function"><span class="keyword">public</span> String <span class="title">getExpiresIn</span><span class="params">()</span> </span>&#123;</span><br><span class="line">		<span class="keyword">return</span> expiresIn;</span><br><span class="line">	&#125;</span><br><span class="line"> </span><br><span class="line">	<span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setExpiresIn</span><span class="params">(String expiresIn)</span> </span>&#123;</span><br><span class="line">		<span class="keyword">this</span>.expiresIn = expiresIn;</span><br><span class="line">	&#125;</span><br><span class="line"> </span><br><span class="line">	<span class="function"><span class="keyword">public</span> String <span class="title">getRefreshToken</span><span class="params">()</span> </span>&#123;</span><br><span class="line">		<span class="keyword">return</span> refreshToken;</span><br><span class="line">	&#125;</span><br><span class="line"> </span><br><span class="line">	<span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setRefreshToken</span><span class="params">(String refreshToken)</span> </span>&#123;</span><br><span class="line">		<span class="keyword">this</span>.refreshToken = refreshToken;</span><br><span class="line">	&#125;</span><br><span class="line"> </span><br><span class="line">	<span class="function"><span class="keyword">public</span> String <span class="title">getOpenId</span><span class="params">()</span> </span>&#123;</span><br><span class="line">		<span class="keyword">return</span> openId;</span><br><span class="line">	&#125;</span><br><span class="line"> </span><br><span class="line">	<span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setOpenId</span><span class="params">(String openId)</span> </span>&#123;</span><br><span class="line">		<span class="keyword">this</span>.openId = openId;</span><br><span class="line">	&#125;</span><br><span class="line"> </span><br><span class="line">	<span class="function"><span class="keyword">public</span> String <span class="title">getScope</span><span class="params">()</span> </span>&#123;</span><br><span class="line">		<span class="keyword">return</span> scope;</span><br><span class="line">	&#125;</span><br><span class="line"> </span><br><span class="line">	<span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setScope</span><span class="params">(String scope)</span> </span>&#123;</span><br><span class="line">		<span class="keyword">this</span>.scope = scope;</span><br><span class="line">	&#125;</span><br><span class="line"> </span><br><span class="line">	<span class="meta">@Override</span></span><br><span class="line">	<span class="function"><span class="keyword">public</span> String <span class="title">toString</span><span class="params">()</span> </span>&#123;</span><br><span class="line">		<span class="keyword">return</span> <span class="string">"accessToken:"</span> + <span class="keyword">this</span>.getAccessToken() + <span class="string">",openId:"</span> + <span class="keyword">this</span>.getOpenId();</span><br><span class="line">	&#125;</span><br><span class="line"> </span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h2 id="WechatUser-java-的实现代码"><a href="#WechatUser-java-的实现代码" class="headerlink" title="WechatUser.java 的实现代码"></a>WechatUser.java 的实现代码</h2><p>这也是一个实体类，用来封装信息的。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> java.io.Serializable;</span><br><span class="line"> </span><br><span class="line"><span class="keyword">import</span> com.fasterxml.jackson.annotation.JsonProperty;</span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 微信用户实体类</span></span><br><span class="line"><span class="comment"> *</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">WechatUser</span> <span class="keyword">implements</span> <span class="title">Serializable</span> </span>&#123;</span><br><span class="line"> </span><br><span class="line">	<span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> <span class="keyword">long</span> serialVersionUID = -<span class="number">4681067645282292327L</span>;</span><br><span class="line"> </span><br><span class="line">	<span class="comment">// openId，标识该公众号下面的该用户的唯一Id</span></span><br><span class="line">	<span class="meta">@JsonProperty</span>(<span class="string">"openid"</span>)</span><br><span class="line">	<span class="keyword">private</span> String openId;</span><br><span class="line">	<span class="comment">// 用户昵称</span></span><br><span class="line">	<span class="meta">@JsonProperty</span>(<span class="string">"nick_name"</span>)</span><br><span class="line">	<span class="keyword">private</span> String nickName;</span><br><span class="line">	<span class="comment">// 性别</span></span><br><span class="line">	<span class="meta">@JsonProperty</span>(<span class="string">"sex"</span>)</span><br><span class="line">	<span class="keyword">private</span> <span class="keyword">int</span> sex;</span><br><span class="line">	<span class="comment">// 省份</span></span><br><span class="line">	<span class="meta">@JsonProperty</span>(<span class="string">"province"</span>)</span><br><span class="line">	<span class="keyword">private</span> String province;</span><br><span class="line">	<span class="comment">// 诚实</span></span><br><span class="line">	<span class="meta">@JsonProperty</span>(<span class="string">"city"</span>)</span><br><span class="line">	<span class="keyword">private</span> String city;</span><br><span class="line">	<span class="comment">// 区</span></span><br><span class="line">	<span class="meta">@JsonProperty</span>(<span class="string">"country"</span>)</span><br><span class="line">	<span class="keyword">private</span> String country;</span><br><span class="line">	<span class="comment">// 头像图片地址</span></span><br><span class="line">	<span class="meta">@JsonProperty</span>(<span class="string">"headimgurl"</span>)</span><br><span class="line">	<span class="keyword">private</span> String headimgurl;</span><br><span class="line">	<span class="comment">// 语言</span></span><br><span class="line">	<span class="meta">@JsonProperty</span>(<span class="string">"language"</span>)</span><br><span class="line">	<span class="keyword">private</span> String language;</span><br><span class="line">	<span class="comment">// 用户权限，这里没什么作用</span></span><br><span class="line">	<span class="meta">@JsonProperty</span>(<span class="string">"privilege"</span>)</span><br><span class="line">	<span class="keyword">private</span> String[] privilege;</span><br><span class="line"> </span><br><span class="line">	<span class="function"><span class="keyword">public</span> String <span class="title">getOpenId</span><span class="params">()</span> </span>&#123;</span><br><span class="line">		<span class="keyword">return</span> openId;</span><br><span class="line">	&#125;</span><br><span class="line"> </span><br><span class="line">	<span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setOpenId</span><span class="params">(String openId)</span> </span>&#123;</span><br><span class="line">		<span class="keyword">this</span>.openId = openId;</span><br><span class="line">	&#125;</span><br><span class="line"> </span><br><span class="line">	<span class="function"><span class="keyword">public</span> String <span class="title">getNickName</span><span class="params">()</span> </span>&#123;</span><br><span class="line">		<span class="keyword">return</span> nickName;</span><br><span class="line">	&#125;</span><br><span class="line"> </span><br><span class="line">	<span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setNickName</span><span class="params">(String nickName)</span> </span>&#123;</span><br><span class="line">		<span class="keyword">this</span>.nickName = nickName;</span><br><span class="line">	&#125;</span><br><span class="line"> </span><br><span class="line">	<span class="function"><span class="keyword">public</span> <span class="keyword">int</span> <span class="title">getSex</span><span class="params">()</span> </span>&#123;</span><br><span class="line">		<span class="keyword">return</span> sex;</span><br><span class="line">	&#125;</span><br><span class="line"> </span><br><span class="line">	<span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setSex</span><span class="params">(<span class="keyword">int</span> sex)</span> </span>&#123;</span><br><span class="line">		<span class="keyword">this</span>.sex = sex;</span><br><span class="line">	&#125;</span><br><span class="line"> </span><br><span class="line">	<span class="function"><span class="keyword">public</span> String <span class="title">getProvince</span><span class="params">()</span> </span>&#123;</span><br><span class="line">		<span class="keyword">return</span> province;</span><br><span class="line">	&#125;</span><br><span class="line"> </span><br><span class="line">	<span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setProvince</span><span class="params">(String province)</span> </span>&#123;</span><br><span class="line">		<span class="keyword">this</span>.province = province;</span><br><span class="line">	&#125;</span><br><span class="line"> </span><br><span class="line">	<span class="function"><span class="keyword">public</span> String <span class="title">getCity</span><span class="params">()</span> </span>&#123;</span><br><span class="line">		<span class="keyword">return</span> city;</span><br><span class="line">	&#125;</span><br><span class="line"> </span><br><span class="line">	<span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setCity</span><span class="params">(String city)</span> </span>&#123;</span><br><span class="line">		<span class="keyword">this</span>.city = city;</span><br><span class="line">	&#125;</span><br><span class="line"> </span><br><span class="line">	<span class="function"><span class="keyword">public</span> String <span class="title">getCountry</span><span class="params">()</span> </span>&#123;</span><br><span class="line">		<span class="keyword">return</span> country;</span><br><span class="line">	&#125;</span><br><span class="line"> </span><br><span class="line">	<span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setCountry</span><span class="params">(String country)</span> </span>&#123;</span><br><span class="line">		<span class="keyword">this</span>.country = country;</span><br><span class="line">	&#125;</span><br><span class="line"> </span><br><span class="line">	<span class="function"><span class="keyword">public</span> String <span class="title">getHeadimgurl</span><span class="params">()</span> </span>&#123;</span><br><span class="line">		<span class="keyword">return</span> headimgurl;</span><br><span class="line">	&#125;</span><br><span class="line"> </span><br><span class="line">	<span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setHeadimgurl</span><span class="params">(String headimgurl)</span> </span>&#123;</span><br><span class="line">		<span class="keyword">this</span>.headimgurl = headimgurl;</span><br><span class="line">	&#125;</span><br><span class="line"> </span><br><span class="line">	<span class="function"><span class="keyword">public</span> String <span class="title">getLanguage</span><span class="params">()</span> </span>&#123;</span><br><span class="line">		<span class="keyword">return</span> language;</span><br><span class="line">	&#125;</span><br><span class="line"> </span><br><span class="line">	<span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setLanguage</span><span class="params">(String language)</span> </span>&#123;</span><br><span class="line">		<span class="keyword">this</span>.language = language;</span><br><span class="line">	&#125;</span><br><span class="line"> </span><br><span class="line">	<span class="keyword">public</span> String[] getPrivilege() &#123;</span><br><span class="line">		<span class="keyword">return</span> privilege;</span><br><span class="line">	&#125;</span><br><span class="line"> </span><br><span class="line">	<span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setPrivilege</span><span class="params">(String[] privilege)</span> </span>&#123;</span><br><span class="line">		<span class="keyword">this</span>.privilege = privilege;</span><br><span class="line">	&#125;</span><br><span class="line"> </span><br><span class="line">	<span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">long</span> <span class="title">getSerialversionuid</span><span class="params">()</span> </span>&#123;</span><br><span class="line">		<span class="keyword">return</span> serialVersionUID;</span><br><span class="line">	&#125;</span><br><span class="line"> </span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h2 id="WechatUtil-java-的实现代码"><a href="#WechatUtil-java-的实现代码" class="headerlink" title="WechatUtil.java 的实现代码"></a>WechatUtil.java 的实现代码</h2><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br><span class="line">117</span><br><span class="line">118</span><br><span class="line">119</span><br><span class="line">120</span><br><span class="line">121</span><br><span class="line">122</span><br><span class="line">123</span><br><span class="line">124</span><br><span class="line">125</span><br><span class="line">126</span><br><span class="line">127</span><br><span class="line">128</span><br><span class="line">129</span><br><span class="line">130</span><br><span class="line">131</span><br><span class="line">132</span><br><span class="line">133</span><br><span class="line">134</span><br><span class="line">135</span><br><span class="line">136</span><br><span class="line">137</span><br><span class="line">138</span><br><span class="line">139</span><br><span class="line">140</span><br><span class="line">141</span><br><span class="line">142</span><br><span class="line">143</span><br><span class="line">144</span><br><span class="line">145</span><br><span class="line">146</span><br><span class="line">147</span><br><span class="line">148</span><br><span class="line">149</span><br><span class="line">150</span><br><span class="line">151</span><br><span class="line">152</span><br><span class="line">153</span><br><span class="line">154</span><br><span class="line">155</span><br><span class="line">156</span><br><span class="line">157</span><br><span class="line">158</span><br><span class="line">159</span><br><span class="line">160</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> java.io.BufferedReader;</span><br><span class="line"><span class="keyword">import</span> java.io.IOException;</span><br><span class="line"><span class="keyword">import</span> java.io.InputStream;</span><br><span class="line"><span class="keyword">import</span> java.io.InputStreamReader;</span><br><span class="line"><span class="keyword">import</span> java.io.OutputStream;</span><br><span class="line"><span class="keyword">import</span> java.net.ConnectException;</span><br><span class="line"><span class="keyword">import</span> java.net.URL;</span><br><span class="line"> </span><br><span class="line"><span class="keyword">import</span> javax.net.ssl.HttpsURLConnection;</span><br><span class="line"><span class="keyword">import</span> javax.net.ssl.SSLContext;</span><br><span class="line"><span class="keyword">import</span> javax.net.ssl.SSLSocketFactory;</span><br><span class="line"><span class="keyword">import</span> javax.net.ssl.TrustManager;</span><br><span class="line"> </span><br><span class="line"><span class="keyword">import</span> org.slf4j.Logger;</span><br><span class="line"><span class="keyword">import</span> org.slf4j.LoggerFactory;</span><br><span class="line"> </span><br><span class="line"><span class="keyword">import</span> com.controller.wechat.WechatLoginController;</span><br><span class="line"><span class="keyword">import</span> com.dto.UserAccessToken;</span><br><span class="line"><span class="keyword">import</span> com.dto.WechatUser;</span><br><span class="line"><span class="keyword">import</span> com.fasterxml.jackson.core.JsonParseException;</span><br><span class="line"><span class="keyword">import</span> com.fasterxml.jackson.databind.JsonMappingException;</span><br><span class="line"><span class="keyword">import</span> com.fasterxml.jackson.databind.ObjectMapper;</span><br><span class="line"> </span><br><span class="line"><span class="keyword">import</span> net.sf.json.JSONObject;</span><br><span class="line"> </span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">WechatUtil</span> </span>&#123;</span><br><span class="line">	<span class="keyword">private</span> <span class="keyword">static</span> Logger log = LoggerFactory.getLogger(WechatLoginController.class);</span><br><span class="line"> </span><br><span class="line">	<span class="comment">/**</span></span><br><span class="line"><span class="comment">	 * 获取UserAccessToken实体类</span></span><br><span class="line"><span class="comment">	 * </span></span><br><span class="line"><span class="comment">	 * <span class="doctag">@param</span> code</span></span><br><span class="line"><span class="comment">	 * <span class="doctag">@return</span></span></span><br><span class="line"><span class="comment">	 */</span></span><br><span class="line">	<span class="function"><span class="keyword">public</span> <span class="keyword">static</span> UserAccessToken <span class="title">getUserAccessToken</span><span class="params">(String code)</span> </span>&#123;</span><br><span class="line">		<span class="comment">// 测试号信息里的appId</span></span><br><span class="line">		String appId = <span class="string">"wxaxxxxxxxxxxxxxxxxx"</span>;</span><br><span class="line">		log.debug(<span class="string">"appId:"</span> + appId);</span><br><span class="line">		<span class="comment">// 测试号信息里的appsecret</span></span><br><span class="line">		String appsecret = <span class="string">"6dxxxxxxxxxxxxxxxxxxxxxxxxxx"</span>;</span><br><span class="line">		log.debug(<span class="string">"appsecret:"</span> + appsecret);</span><br><span class="line">		<span class="comment">// 根据传入的code，拼接出访问微信定义好的接口的URL</span></span><br><span class="line">		String url = <span class="string">"https://api.weixin.qq.com/sns/oauth2/access_token?appid="</span> + appId + <span class="string">"&amp;secret="</span> + appsecret</span><br><span class="line">				+ <span class="string">"&amp;code="</span> + code + <span class="string">"&amp;grant_type=authorization_code"</span>;</span><br><span class="line">		<span class="comment">// 向相应URL发送请求获取token json字符串</span></span><br><span class="line">		String tokenStr = httpsRequest(url, <span class="string">"GET"</span>, <span class="keyword">null</span>).toString();</span><br><span class="line">		log.debug(<span class="string">"userAccessToken:"</span> + tokenStr);</span><br><span class="line">		UserAccessToken token = <span class="keyword">new</span> UserAccessToken();</span><br><span class="line">		ObjectMapper objectMapper = <span class="keyword">new</span> ObjectMapper();</span><br><span class="line">		<span class="keyword">try</span> &#123;</span><br><span class="line">			<span class="comment">// 将json字符串转换成相应对象</span></span><br><span class="line">			token = objectMapper.readValue(tokenStr, UserAccessToken.class);</span><br><span class="line">		&#125; <span class="keyword">catch</span> (JsonParseException e) &#123;</span><br><span class="line">			log.error(<span class="string">"获取用户accessToken失败:"</span> + e.getMessage());</span><br><span class="line">			e.printStackTrace();</span><br><span class="line">		&#125; <span class="keyword">catch</span> (JsonMappingException e) &#123;</span><br><span class="line">			log.error(<span class="string">"获取用户accessToken失败:"</span> + e.getMessage());</span><br><span class="line">			e.printStackTrace();</span><br><span class="line">		&#125; <span class="keyword">catch</span> (IOException e) &#123;</span><br><span class="line">			log.error(<span class="string">"获取用户accessToken失败:"</span> + e.getMessage());</span><br><span class="line">			e.printStackTrace();</span><br><span class="line">		&#125;</span><br><span class="line">		<span class="keyword">if</span> (token == <span class="keyword">null</span>) &#123;</span><br><span class="line">			log.error(<span class="string">"获取用户accessToken失败."</span>);</span><br><span class="line">			<span class="keyword">return</span> <span class="keyword">null</span>;</span><br><span class="line">		&#125;</span><br><span class="line">		<span class="keyword">return</span> token;</span><br><span class="line">	&#125;</span><br><span class="line"> </span><br><span class="line">	<span class="comment">/**</span></span><br><span class="line"><span class="comment">	 * 发起https请求并获取结果</span></span><br><span class="line"><span class="comment">	 * </span></span><br><span class="line"><span class="comment">	 * <span class="doctag">@param</span> requestUrl</span></span><br><span class="line"><span class="comment">	 *            请求地址</span></span><br><span class="line"><span class="comment">	 * <span class="doctag">@param</span> requestMethod</span></span><br><span class="line"><span class="comment">	 *            请求方式（GET、post）</span></span><br><span class="line"><span class="comment">	 * <span class="doctag">@param</span> outputStr</span></span><br><span class="line"><span class="comment">	 *            提交的数据</span></span><br><span class="line"><span class="comment">	 * <span class="doctag">@return</span> json字符串</span></span><br><span class="line"><span class="comment">	 */</span></span><br><span class="line">	<span class="function"><span class="keyword">private</span> <span class="keyword">static</span> JSONObject <span class="title">httpsRequest</span><span class="params">(String requestUrl, String requestMethod, String outputStr)</span> </span>&#123;</span><br><span class="line">		StringBuffer buffer = <span class="keyword">new</span> StringBuffer();</span><br><span class="line">		JSONObject jsonObject = <span class="keyword">null</span>;</span><br><span class="line">		<span class="keyword">try</span> &#123;</span><br><span class="line">			<span class="comment">// 创建SSLContext对象，并使用我们制定的信任管理器初始化</span></span><br><span class="line">			TrustManager[] tm = &#123; <span class="keyword">new</span> MyX509TrustManager() &#125;;</span><br><span class="line">			SSLContext sslContext = SSLContext.getInstance(<span class="string">"SSL"</span>, <span class="string">"SunJSSE"</span>);</span><br><span class="line">			sslContext.init(<span class="keyword">null</span>, tm, <span class="keyword">new</span> java.security.SecureRandom());</span><br><span class="line">			<span class="comment">// 从上述SSLContext对象中得到SSLSocketFactory对象</span></span><br><span class="line">			SSLSocketFactory ssf = sslContext.getSocketFactory();</span><br><span class="line"> </span><br><span class="line">			URL url = <span class="keyword">new</span> URL(requestUrl);</span><br><span class="line">			HttpsURLConnection httpUrlConn = (HttpsURLConnection) url.openConnection();</span><br><span class="line">			httpUrlConn.setSSLSocketFactory(ssf);</span><br><span class="line"> </span><br><span class="line">			httpUrlConn.setDoOutput(<span class="keyword">true</span>);</span><br><span class="line">			httpUrlConn.setDoInput(<span class="keyword">true</span>);</span><br><span class="line">			httpUrlConn.setUseCaches(<span class="keyword">false</span>);</span><br><span class="line">			<span class="comment">// 设置请求方式（GET/POST）</span></span><br><span class="line">			httpUrlConn.setRequestMethod(requestMethod);</span><br><span class="line"> </span><br><span class="line">			<span class="keyword">if</span> (<span class="string">"GET"</span>.equalsIgnoreCase(requestMethod)) &#123;</span><br><span class="line">				httpUrlConn.connect();</span><br><span class="line">			&#125;</span><br><span class="line"> </span><br><span class="line">			<span class="comment">// 当有数据需要提交时</span></span><br><span class="line">			<span class="keyword">if</span> (<span class="keyword">null</span> != outputStr) &#123;</span><br><span class="line">				OutputStream outputStream = httpUrlConn.getOutputStream();</span><br><span class="line">				<span class="comment">// 注意编码格式，防止中文乱码</span></span><br><span class="line">				outputStream.write(outputStr.getBytes(<span class="string">"UTF-8"</span>));</span><br><span class="line">				outputStream.close();</span><br><span class="line">			&#125;</span><br><span class="line"> </span><br><span class="line">			<span class="comment">// 将返回的输入流转换成字符串</span></span><br><span class="line">			InputStream inputStream = httpUrlConn.getInputStream();</span><br><span class="line">			InputStreamReader inputStreamReader = <span class="keyword">new</span> InputStreamReader(inputStream, <span class="string">"utf-8"</span>);</span><br><span class="line">			BufferedReader bufferedReader = <span class="keyword">new</span> BufferedReader(inputStreamReader);</span><br><span class="line"> </span><br><span class="line">			String str = <span class="keyword">null</span>;</span><br><span class="line">			<span class="keyword">while</span> ((str = bufferedReader.readLine()) != <span class="keyword">null</span>) &#123;</span><br><span class="line">				buffer.append(str);</span><br><span class="line">			&#125;</span><br><span class="line">			bufferedReader.close();</span><br><span class="line">			inputStreamReader.close();</span><br><span class="line">			<span class="comment">// 释放资源</span></span><br><span class="line">			inputStream.close();</span><br><span class="line">			inputStream = <span class="keyword">null</span>;</span><br><span class="line">			httpUrlConn.disconnect();</span><br><span class="line">			log.debug(<span class="string">"https buffer:"</span> + buffer.toString());</span><br><span class="line">		&#125; <span class="keyword">catch</span> (ConnectException ce) &#123;</span><br><span class="line">			log.error(<span class="string">"Wechat server connection timed out"</span>);</span><br><span class="line">		&#125; <span class="keyword">catch</span> (Exception e) &#123;</span><br><span class="line">			log.error(<span class="string">"https request error:&#123;&#125;"</span>, e);</span><br><span class="line">		&#125;</span><br><span class="line">		jsonObject = JSONObject.fromObject(buffer.toString());</span><br><span class="line">		<span class="keyword">return</span> jsonObject;</span><br><span class="line">	&#125;</span><br><span class="line"> </span><br><span class="line">	<span class="function"><span class="keyword">public</span> <span class="keyword">static</span> WechatUser <span class="title">getUserInfo</span><span class="params">(String accessToken, String openId)</span> </span>&#123;</span><br><span class="line">		String url = <span class="string">"https://api.weixin.qq.com/sns/userinfo?access_token="</span> + accessToken + <span class="string">"&amp;openid="</span> + openId</span><br><span class="line">				+ <span class="string">"&amp;lang=zh_CN"</span>;</span><br><span class="line">		JSONObject jsonObject = WechatUtil.httpsRequest(url, <span class="string">"GET"</span>, <span class="keyword">null</span>);</span><br><span class="line">		WechatUser user = <span class="keyword">new</span> WechatUser();</span><br><span class="line">		String openid = jsonObject.getString(<span class="string">"openid"</span>);</span><br><span class="line">		<span class="keyword">if</span> (openid == <span class="keyword">null</span>) &#123;</span><br><span class="line">			log.debug(<span class="string">"获取用户信息失败。"</span>);</span><br><span class="line">			<span class="keyword">return</span> <span class="keyword">null</span>;</span><br><span class="line">		&#125;</span><br><span class="line">		user.setOpenId(openid);</span><br><span class="line">		user.setNickName(jsonObject.getString(<span class="string">"nickname"</span>));</span><br><span class="line">		user.setSex(jsonObject.getInt(<span class="string">"sex"</span>));</span><br><span class="line">		user.setProvince(jsonObject.getString(<span class="string">"province"</span>));</span><br><span class="line">		user.setCity(jsonObject.getString(<span class="string">"city"</span>));</span><br><span class="line">		user.setCountry(jsonObject.getString(<span class="string">"country"</span>));</span><br><span class="line">		user.setHeadimgurl(jsonObject.getString(<span class="string">"headimgurl"</span>));</span><br><span class="line">		user.setPrivilege(<span class="keyword">null</span>);</span><br><span class="line">		<span class="comment">// user.setUnionid(jsonObject.getString("unionid"));</span></span><br><span class="line">		<span class="keyword">return</span> user;</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<table><tr><td bgcolor="#C0FF3E">解析：</td></tr></table>

<ul>
<li>获取 <font color="red">UserAccessToken</font> 工具类，需要修改的是开头的两个地方：</li>
</ul>
<p><img src="http://zwd.yyzheng.cn/wechat_account/cb4f47f9058d6bb2s.png" alt="Markdown"></p>
<ul>
<li><p>我代码里提供的是乱码，所以这里需要把 appid 和 appsecret 修改为自己的，至于在哪里找？？？你进入自己申请好的微信测试号就行看到了。</p>
</li>
<li><p>代码里面还使用到 JSONObject 这个类，关于这个类的相关 jar 包的引入，之前另一篇博客写过，直接看下就行。博客链接：<a href="https://blog.csdn.net/weidong_y/article/details/81141694" target="_blank" rel="noopener">JSONObject 使用maven引入 net.sf.json 时报错解决方法</a></p>
</li>
</ul>
<h2 id="MyX509TrustManager-java-的实现代码"><a href="#MyX509TrustManager-java-的实现代码" class="headerlink" title="MyX509TrustManager.java 的实现代码"></a>MyX509TrustManager.java 的实现代码</h2><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> java.security.cert.CertificateException;</span><br><span class="line"><span class="keyword">import</span> java.security.cert.X509Certificate;</span><br><span class="line"> </span><br><span class="line"><span class="keyword">import</span> javax.net.ssl.X509TrustManager;</span><br><span class="line"> </span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 证书信任管理器（用于https请求）</span></span><br><span class="line"><span class="comment"> *</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">MyX509TrustManager</span> <span class="keyword">implements</span> <span class="title">X509TrustManager</span></span>&#123;</span><br><span class="line"> </span><br><span class="line">	<span class="meta">@Override</span></span><br><span class="line">	<span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">checkClientTrusted</span><span class="params">(X509Certificate[] chain, String authType)</span> <span class="keyword">throws</span> CertificateException </span>&#123;</span><br><span class="line">		<span class="comment">// TODO Auto-generated method stub</span></span><br><span class="line">		</span><br><span class="line">	&#125;</span><br><span class="line"> </span><br><span class="line">	<span class="meta">@Override</span></span><br><span class="line">	<span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">checkServerTrusted</span><span class="params">(X509Certificate[] chain, String authType)</span> <span class="keyword">throws</span> CertificateException </span>&#123;</span><br><span class="line">		<span class="comment">// TODO Auto-generated method stub</span></span><br><span class="line">		</span><br><span class="line">	&#125;</span><br><span class="line"> </span><br><span class="line">	<span class="meta">@Override</span></span><br><span class="line">	<span class="keyword">public</span> X509Certificate[] getAcceptedIssuers() &#123;</span><br><span class="line">		<span class="comment">// TODO Auto-generated method stub</span></span><br><span class="line">		<span class="keyword">return</span> <span class="keyword">null</span>;</span><br><span class="line">	&#125;</span><br><span class="line"> </span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>只是直接继承了 X509TrustManager 这个接口，并实现接口里面的方法，并不需要自己写什么。</p>
<p>到这里，需要实现的 java 类都实现了，同样的道理，需要把整个项目导出 jar 包，然后扔到服务器上。不然访问不到！！！</p>
<h1 id="尝试连接微信测试号"><a href="#尝试连接微信测试号" class="headerlink" title="尝试连接微信测试号"></a>尝试连接微信测试号</h1><p>登录微信测试号页面，找到测试号二维码，然后用自己的微信号扫码，使自己的微信账号位于用户列表中。</p>
<p><img src="http://zwd.yyzheng.cn/wechat_account/a8868c989a23befes.png" alt="Markdown"></p>
<p>然后，在微信上直接打开下面的链接：</p>
<p><a href="https://open.weixin.qq.com/connect/oauth2/authorize?appid=xxxxxx&amp;redirect_uri=https://www.xxxxxx.cn/o2o/wechatlogin/logincheck&amp;role_type=1&amp;response_type=1&amp;response_type=code&amp;scope=snsapi_userinfo&amp;state=1#wechat_redirect" target="_blank" rel="noopener">https://open.weixin.qq.com/connect/oauth2/authorize?appid=xxxxxx&amp;redirect_uri=https://www.xxxxxx.cn/o2o/wechatlogin/logincheck&amp;role_type=1&amp;response_type=1&amp;response_type=code&amp;scope=snsapi_userinfo&amp;state=1#wechat_redirect</a> </p>
<p>这个链接，有个参数需要修改下，就是 <font color="red">appid</font> 这个参数后面的值需要换上自己测试号的 appid 哦，还有 redirect_uri 的参数中的域名需要换成自己的域名，还有项目名字如果自己修改了，也要换掉哦。其它的参数不要动。然后把链接发给微信上，用手机微信打开，就能发现成功进入测试号后，会跳转到自己指定的页面。</p>

      
    </div>

    

    
    
    

    <div>
      
        
<div class="my_post_copyright">
  <script src="//cdn.bootcss.com/clipboard.js/1.5.10/clipboard.min.js"></script>
  
  <!-- JS库 sweetalert 可修改路径 -->
  <script src="https://cdn.bootcss.com/jquery/2.0.0/jquery.min.js"></script>
  <script src="https://unpkg.com/sweetalert/dist/sweetalert.min.js"></script>
  <p><span>本文标题:</span><a href="/blog/2019/04/16/wechat_account/">从零接入微信公众号（附源码+解说）</a></p>
  <p><span>文章作者:</span><a href="/" title="访问 小东 的个人博客">小东</a></p>
  <p><span>发布时间:</span>2019年04月16日 - 00:04</p>
  <p><span>最后更新:</span>2019年05月13日 - 10:05</p>
  <p><span>原始链接:</span><a href="/blog/2019/04/16/wechat_account/" title="从零接入微信公众号（附源码+解说）">http://zwd596257180.gitee.io/2019/04/16/wechat_account/</a>
    <span class="copy-path" title="点击复制文章链接"><i class="fa fa-clipboard" data-clipboard-text="http://zwd596257180.gitee.io/2019/04/16/wechat_account/" aria-label="复制成功！"></i></span>
  </p>
  <p><span>许可协议:</span><i class="fa fa-creative-commons"></i> 转载请保留原文链接及作者。</p>  
</div>
<script> 
    var clipboard = new Clipboard('.fa-clipboard');
    $(".fa-clipboard").click(function(){
      clipboard.on('success', function(){
        swal({   
          title: "",   
          text: '复制成功',
          icon: "success", 
          showConfirmButton: true
          });
    });
    });  
</script>

      
    </div>

    
      <div id="wechat_subscriber" style="display: block; padding: 10px 0; margin: 20px auto; width: 100%; text-align: center;">
  <img id="wechat_subscriber_qcode" src="/blog/uploads/wechat-qcode.jpg" alt="小东 wechat" style="width: 200px; max-width: 100%;">
  <div>欢迎您扫一扫上面的微信公众号，订阅我的博客！</div>
</div>

    

    
      
    
    
      <div>
        <div id="reward-container">
  <div></div>
  <button id="reward-button" disable="enable" onclick="var qr = document.getElementById(&quot;qr&quot;); qr.style.display = (qr.style.display === 'none') ? 'block' : 'none';">
    打赏
  </button>
  <div id="qr" style="display: none;">

    
      
      
        
      
      <div style="display: inline-block">
        <img src="/blog/uploads/wechat-reword-image.png" alt="小东 微信支付">
        <p>微信支付</p>
      </div>
    
      
      
        
      
      <div style="display: inline-block">
        <img src="/blog/uploads/alipay-reword-image.png" alt="小东 支付宝">
        <p>支付宝</p>
      </div>
    

  </div>
</div>

      </div>
    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/blog/tags/微信/" rel="tag"><i class="fa fa-tag"></i> 微信</a>
          
            <a href="/blog/tags/公众号/" rel="tag"><i class="fa fa-tag"></i> 公众号</a>
          
            <a href="/blog/tags/Java/" rel="tag"><i class="fa fa-tag"></i> Java</a>
          
        </div>
      

      
      
        <div class="post-widgets">
        

        

        
          
          <div class="social_share">
            
            
            
              <div>
                
  <div class="bdsharebuttonbox">
    <a href="#" class="bds_tsina" data-cmd="tsina" title="分享到新浪微博"></a>
    <a href="#" class="bds_douban" data-cmd="douban" title="分享到豆瓣网"></a>
    <a href="#" class="bds_sqq" data-cmd="sqq" title="分享到QQ好友"></a>
    <a href="#" class="bds_qzone" data-cmd="qzone" title="分享到QQ空间"></a>
    <a href="#" class="bds_weixin" data-cmd="weixin" title="分享到微信"></a>
    <a href="#" class="bds_tieba" data-cmd="tieba" title="分享到百度贴吧"></a>
    <a href="#" class="bds_twi" data-cmd="twi" title="分享到Twitter"></a>
    <a href="#" class="bds_fbook" data-cmd="fbook" title="分享到Facebook"></a>
    <a href="#" class="bds_more" data-cmd="more"></a>
    <a class="bds_count" data-cmd="count"></a>
  </div>
  <script>
    window._bd_share_config = {
      "common": {
        "bdText": "",
        "bdMini": "2",
        "bdMiniList": false,
        "bdPic": ""
      },
      "share": {
        "bdSize": "16",
        "bdStyle": "0"
      },
      "image": {
        "viewList": ["tsina", "douban", "sqq", "qzone", "weixin", "twi", "fbook"],
        "viewText": "分享到：",
        "viewSize": "16"
      }
    }
  </script>

<script>
  with(document)0[(getElementsByTagName('head')[0]||body).appendChild(createElement('script')).src='//bdimg.share.baidu.com/static/api/js/share.js?cdnversion='+~(-new Date()/36e5)];
</script>

              </div>
            
          </div>
        
        </div>
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/blog/2019/04/15/wechat_applet_login/" rel="next" title="微信小程序  授权登录的实现">
                <i class="fa fa-chevron-left"></i> 微信小程序  授权登录的实现
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/blog/2019/04/16/mysql_change_password/" rel="prev" title="忘记 mysql 数据库连接密码，怎么办？">
                忘记 mysql 数据库连接密码，怎么办？ <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>


  </div>


          </div>
          

  
    <div class="comments" id="comments">
      <div id="lv-container" data-id="city" data-uid="MTAyMC80Mzc0MC8yMDI3OQ=="></div>
    </div>

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image" src="https://wx.qlogo.cn/mmopen/vi_32/GqPMLROFPOIvfCs85HKcD1UKwt3zEJOK4yIcJKaSz4lFGTaL8EzBmziczWx9oWbHyAIBcjwAMXviayrzkpYmzzvg/132" alt="小东">
            
              <p class="site-author-name" itemprop="name">小东</p>
              <div class="site-description motion-element" itemprop="description">欢迎您的到来！</div>
          </div>

          <iframe frameborder="no" border="0" marginwidth="0" marginheight="0" width="330" height="86" src="//music.163.com/outchain/player?type=2&id=1325905146&auto=0&height=66"></iframe>

          
            <nav class="site-state motion-element">
              
                <div class="site-state-item site-state-posts">
                
                  <a href="/blog/archives/">
                
                    <span class="site-state-item-count">10</span>
                    <span class="site-state-item-name">日志</span>
                  </a>
                </div>
              

              
                
                
                <div class="site-state-item site-state-categories">
                  
                    
                      <a href="/blog/categories/">
                    
                  
                    
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                    <span class="site-state-item-count">9</span>
                    <span class="site-state-item-name">分类</span>
                  </a>
                </div>
              

              
                
                
                <div class="site-state-item site-state-tags">
                  
                    
                      <a href="/blog/tags/">
                    
                  
                    
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                    <span class="site-state-item-count">14</span>
                    <span class="site-state-item-name">标签</span>
                  </a>
                </div>
              
            </nav>
          

          
            <div class="feed-link motion-element">
              <a href="/blog/atom.xml" rel="alternate">
                <i class="fa fa-rss"></i>
                RSS
              </a>
            </div>
          

          

          
            <div class="links-of-author motion-element">
              
                <span class="links-of-author-item">
                  
                  
                    
                  
                  
                    
                  
                  <a href="https://github.com/yyzheng1729" title="GitHub &rarr; https://github.com/yyzheng1729" rel="noopener" target="_blank"><i class="fa fa-fw fa-github"></i>GitHub</a>
                </span>
              
                <span class="links-of-author-item">
                  
                  
                    
                  
                  
                    
                  
                  <a href="https://blog.csdn.net/weidong_y" title="CSDN &rarr; https://blog.csdn.net/weidong_y" rel="noopener" target="_blank"><i class="fa fa-fw fa-book"></i>CSDN</a>
                </span>
              
                <span class="links-of-author-item">
                  
                  
                    
                  
                  
                    
                  
                  <a href="http://wpa.qq.com/msgrd?v=3&uin=596257180&site=qq&menu=yes" title="QQ &rarr; http://wpa.qq.com/msgrd?v=3&uin=596257180&site=qq&menu=yes" rel="noopener" target="_blank"><i class="fa fa-fw fa-qq"></i>QQ</a>
                </span>
              
                <span class="links-of-author-item">
                  
                  
                    
                  
                  
                    
                  
                  <a href="/blog/596257180@qq.com" title="E-Mail &rarr; 596257180@qq.com"><i class="fa fa-fw fa-envelope"></i>E-Mail</a>
                </span>
              
            </div>
          

          

          
          
            <div class="links-of-blogroll motion-element links-of-blogroll-block">
              <div class="links-of-blogroll-title">
                <i class="fa  fa-fw fa-link"></i>
                友情链接
              </div>
              <ul class="links-of-blogroll-list">
                
                  <li class="links-of-blogroll-item">
                    <a href="https://www.baidu.com/" title="https://www.baidu.com/" rel="noopener" target="_blank">百度</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="https://www.iqiyi.com/" title="https://www.iqiyi.com/" rel="noopener" target="_blank">爱奇艺</a>
                  </li>
                
              </ul>
            </div>
          

          
            
          
          

        </div>
      </div>

      
      <!--noindex-->
        <div class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
            
            
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#前言"><span class="nav-number">1.</span> <span class="nav-text">前言</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#实现接口连接的类"><span class="nav-number">2.</span> <span class="nav-text">实现接口连接的类</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#微信测试号的申请与接口连接"><span class="nav-number">3.</span> <span class="nav-text">微信测试号的申请与接口连接</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#微信测试号连接代码的实现"><span class="nav-number">4.</span> <span class="nav-text">微信测试号连接代码的实现</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#用到类的简介"><span class="nav-number">4.1.</span> <span class="nav-text">用到类的简介</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#WechatLoginController-java-的实现代码"><span class="nav-number">4.2.</span> <span class="nav-text">WechatLoginController.java 的实现代码</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#UserAccessToken-java-的实现代码"><span class="nav-number">4.3.</span> <span class="nav-text">UserAccessToken.java  的实现代码</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#WechatUser-java-的实现代码"><span class="nav-number">4.4.</span> <span class="nav-text">WechatUser.java 的实现代码</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#WechatUtil-java-的实现代码"><span class="nav-number">4.5.</span> <span class="nav-text">WechatUtil.java 的实现代码</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#MyX509TrustManager-java-的实现代码"><span class="nav-number">4.6.</span> <span class="nav-text">MyX509TrustManager.java 的实现代码</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#尝试连接微信测试号"><span class="nav-number">5.</span> <span class="nav-text">尝试连接微信测试号</span></a></li></ol></div>
            

          </div>
        </div>
      <!--/noindex-->
      

      

    </div>
  </aside>
  



        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2019</span>
  <span class="with-love" id="animate">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">小东</span>

  

  
</div>

<!-- 用下面的符号注释，注释代码用下面括号括起来 -->
<!-- -->

<!-- 

  <div class="powered-by">由 <a href="https://hexo.io" class="theme-link" rel="noopener" target="_blank">Hexo</a> 强力驱动 v3.8.0</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 – <a href="https://theme-next.org" class="theme-link" rel="noopener" target="_blank">NexT.Gemini</a> v7.1.0</div>



-->

<script async src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>

<div class="powered-by">
  <i class="fa fa-user-md"></i>
  <span id="busuanzi_container_site_pv">
    本站访问量:<span id="busuanzi_value_site_pv"></span>次
  </span>
  <span class="post-meta-divider">|</span>
  <span id="busuanzi_container_site_uv">
    本站总访客量：<span id="busuanzi_value_site_uv"></span>人
  </span>
</div>

<span class="post-meta-divider">|</span>

<div class="theme-info">
  <div class="powered-by"></div>
  <span class="post-count">博客全站共34.4k字</span>
</div>

        








        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

    

    
  </div>

  

<script>
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>


























  
  <script src="/blog/lib/jquery/index.js?v=2.1.3"></script>

  
  <script src="/blog/lib/velocity/velocity.min.js?v=1.2.1"></script>

  
  <script src="/blog/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>


  


  <script src="/blog/js/utils.js?v=7.1.0"></script>

  <script src="/blog/js/motion.js?v=7.1.0"></script>



  
  


  <script src="/blog/js/affix.js?v=7.1.0"></script>

  <script src="/blog/js/schemes/pisces.js?v=7.1.0"></script>




  
  <script src="/blog/js/scrollspy.js?v=7.1.0"></script>
<script src="/blog/js/post-details.js?v=7.1.0"></script>



  


  <script src="/blog/js/next-boot.js?v=7.1.0"></script>


  

  

  

  


  
    <script>
  window.livereOptions = {
    refer: '2019/04/16/wechat_account/'
  };
  (function(d, s) {
    var j, e = d.getElementsByTagName(s)[0];
    if (typeof LivereTower === 'function') { return; }
    j = d.createElement(s);
    j.src = 'https://cdn-city.livere.com/js/embed.dist.js';
    j.async = true;
    e.parentNode.insertBefore(j, e);
  })(document, 'script');
</script>

  


  
  <script>
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/blog/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url).replace(/\/{2,}/g, '/');
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x"></i></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x"></i></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  

  

  

  

  

  

  

  

  

  

  

  

</body>
</html>

<!-- 动态背景 -->
<script type="text/javascript" src="//cdn.bootcss.com/canvas-nest.js/1.0.0/canvas-nest.min.js"></script>

<!-- 页面点击小红心 -->
<script type="text/javascript" src="/js/src/clicklove.js"></script>
